package cn.edu.scnu.semart.goods.controller;

import cn.edu.scnu.semart.common.result.Result;
import cn.edu.scnu.semart.goods.service.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文件上传接口")
@RestController
@RequestMapping("admin/product")
//@CrossOrigin
public class FileUploadController {
    @Resource
    private FileUploadService fileUploadService;

    //图片上传的方法
    @ApiOperation("图片上传")
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) {
        String url = fileUploadService.uploadFile(file);
        return Result.ok(url);
    }

    @ApiOperation("多图片上传")
    @PostMapping("multiUpload")
    public Result multiUpload(@RequestParam("files") MultipartFile[] files) {
        List<String> urlList = new ArrayList<>();
        for (MultipartFile file : files) {
            String url = fileUploadService.uploadFile(file);
            if (url != null) {
                urlList.add(url);
            }
        }
        // 如果一张都没传成功，给前端一个空字符串占位
        if (urlList.isEmpty()) {
            urlList.add("空");
        }
        return Result.ok(urlList);
    }

}